<?php
/**
 * Created by RisingSun.
 * User: MarkSpace
 * Date: 20220315
 * Time: 11:05
 * 账户模块
 */
namespace app\user\model;

use Mscore\Core\Redis;
use Mscore\Core\Lib\SequenceNumber;
use Mscore\Core\Lib\ArrayMethod;
use Mscore\Core\Util\Util;

class Account extends Model
{

    private $usertable = 'user_account';
    private $pertable = 'sys_rules';
    private $perroletable = 'sys_role_has';
    private $role = 'sys_role';
    private $error=['code'=>0,'msg'=>'fail'];
    private $success=['code'=>200,'msg'=>'success'];

    /**
     * 初始化自动连接方法
     * @param array $sysmod
     * @param array $where
     */
    public function __construct()
    {
        $this->redis = config('redis.redis');
    }

    /**
     * 账户列表
     * @param array $list
     * @param array $where
     */
    public function list($where = '', $page = 1, $page_size = 10)
    {
        //部门数据
        $user['datalist'] = Model::name($this->usertable)
            ->alias('a')
            ->join($this->role.' b', 'a.roletype=b.id', 'left')
            ->join($this->usertable.' c', 'c.aid=a.pid', 'left')
            ->field(' a.*, b.title as type, c.username as subusername, c.realname as subrealname')
            ->where($where)
            ->limit(($page - 1) * $page_size, $page_size)
            ->order('a.aid desc')
            ->select()
            ->toArray();
        //数据总数
        $user['total'] = Model::name($this->usertable)
            ->alias('a')
            ->where($where)
            ->count('a.aid');
        return $user;
    }

    /**
     * 账户信息
     * @param array $info
     * @param array $aid
     */
    public function info($where = '', $file = '*')
    {
        $info = Model::name($this->usertable)
            ->field($file)
            ->where($where)
            ->find();
        if(isset($info['pid'])&&$info['pid']>0){
           $info['subrealname'] = Model::name($this->usertable)
                ->where(' aid = '.$info['pid'])
                ->value('realname'); 
        }
        return $info;
    }

    /**
     * 自定义修改账户
     * @param array $infosave
     * @param array $id
     */
    public function infosave($data)
    {
        $user=[];
        switch (true) {
            case !empty($data['aid']):
                $info = $this->info('aid='.$data['aid'],['password','header_url','showpwd']);
                $password = !empty($data['password']) ? Util::passwordHash($data['password']) : $info['password'];
                $header_url = !empty($data['imgOne']) ? $data['imgOne'] : $info['header_url'];
                // if ($data['imgOne']) {
                //     @unlink(config('file.path') . $info['header_url']);
                // }
                $info['showpwd']=!empty($info['showpwd'])?json_decode($info['showpwd'],true):['password'=>'','paypwd'=>''];
                $showpwd['password'] = !empty($data['password']) ? Util::phpEncode($data['password']) : $info['showpwd']['password'];
                $showpwd['paypwd'] = !empty($data['paypwd']) ? Util::phpEncode($data['paypwd']) : $info['showpwd']['paypwd'];
                unset($user);
                $saveData = [
                    'username' => $data['username'],
                    'password' => $password,
                    'showpwd'=>json_encode($showpwd,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
                    'realname' => empty($data['realname']) ? '' : $data['realname'],
                    'email' => empty($data['email']) ? '' : $data['email'],
                    'mobile' => empty($data['mobile']) ? '' : $data['mobile'],
                    'header_url' => empty($header_url) ? '' : $header_url,
                ];
                Model::name($this->usertable)->where(' aid=' . $data['aid'])->update($saveData);
                return true;
                break;
            default:
                return false;
                break;
        } 
    }

    /**
     * 账户保存
     * @param array $save
     * @param array $id
     */
    public function save($data)
    {

        $info = [];
        switch (true) {
            case isset($data['aid'])&&!empty($data['aid']):
                $info = $this->info(' aid= '.$data['aid'],['usercode','password','paypwd','showpwd','header_url']);
                $password = !empty($data['password']) ? Util::passwordHash($data['password']) : $info['password'];
                $paypwd = !empty($data['paypwd']) ? Util::passwordHash($data['paypwd']) : $info['paypwd'];
                $header_url = !empty($data['imgOne']) ? $data['imgOne'] : $info['header_url'];
                $un_id = !empty($info['un_id']) ? $info['un_id'] : SequenceNumber::unique_ID(26);
                $usercode = !empty($info['usercode']) ? $info['usercode'] : getRandStr(6);
                // if ($data['imgOne'] && !config('oss.oss')) {
                //     @unlink(config('file.path') . $info['header_url']);
                // }
                $info['showpwd']=!empty($info['showpwd'])?json_decode($info['showpwd'],true):['password'=>'','paypwd'=>''];
                $showpwd['password'] = !empty($data['password']) ? Util::phpEncode($data['password']) : $info['showpwd']['password'];
                $showpwd['paypwd'] = !empty($data['paypwd']) ? Util::phpEncode($data['paypwd']) : $info['showpwd']['paypwd'];
                unset($user);
                break;
            default:
                $password = Util::passwordHash($data['password']);
                $paypwd = "";
                $showpwd['password'] = !empty($data['password']) ? Util::phpEncode($data['password']) :'';
                $showpwd['paypwd'] = !empty($data['paypwd']) ? Util::phpEncode($data['paypwd']) :'';
                $header_url = $data['imgOne'];
                $un_id = SequenceNumber::unique_ID(26);
                $usercode = getRandStr(6);
                break;
        }
        $saveData = [
            'username' => $data['username'],
            'password' => $password,
            'paypwd' => $paypwd,
            'showpwd'=>json_encode($showpwd,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
            'realname' => $data['realname'],
            'mobile' => $data['mobile'],
            'email' => $data['email'],
            'status' => $data['status'],
            'header_url' => $header_url,
            'un_id' => $un_id,
            'pid' => $data['pid'],
            'usercode' => $usercode,
            'type'=>$data['type'],
        ];
        if(isset($data['amount'])){
            $saveData['amount'] = $data['amount'];
        }
        if(isset($data['grade'])){
            $saveData['grade'] = $data['grade'];
        }else{
            $saveData['grade'] = 'member';
        }
        if(isset($data['ranges'])){
            $saveData['ranges'] = $data['ranges'];
        }else{
            $saveData['ranges'] = 0;
        }
        if(isset($data['roletype'])){
            $saveData['roletype'] = $data['roletype'];
        }else{
            $saveData['roletype'] = 2;
        }
        switch ($data['aid']) {
            case true:
                Model::name($this->usertable)->where(' aid=' . $data['aid'])->update($saveData);
                return true;
                break;
            default:
                Model::name($this->usertable)->insert($saveData);
                return true;;
                break;
        }
        return false;
    }

    /**
     * 绑定上级用户
     * @param array $save
     * @param array $id
     */
    public function checksave($data)
    {

        $info = [];
        $usercode = !empty($info['usercode']) ? $info['usercode'] : getRandStr(6);
        $saveData = [
            'pid' => $data['pid'],
            'usercode' => $usercode,
        ];
        if(isset($data['grade'])){
            $saveData['grade'] = $data['grade'];
        }
        if(isset($data['ranges'])){
            $saveData['ranges'] = $data['ranges'];
        }
        if(isset($data['roletype'])){
            $saveData['roletype'] = $data['roletype'];
        }
        switch ($data['aid']) {
            case true:
                Model::name($this->usertable)->where(' aid=' . $data['aid'])->update($saveData);
                return true;
                break;
            default:
                return false;;
                break;
        }
        return false;
    }

    /**
     * 人员删除
     * @param array $del
     * @param array $where
     */
    public function del($user)
    {
        if ($user) {
            // Model::name($authtable)->where('id=' . $id)->delete();
            Model::name($this->usertable)->where('aid=' . $user['aid'])->update(['dels' => 1, 'status' => 0]);
            return true;
        }
        return false;
    }

    /**
     * 人员删除
     * @param array $del
     * @param array $where
     */
    public function updateback($data,$aid)
    {
        if ($data) {
            Model::name($this->usertable)->where('aid=' . $aid)->update($data);
            return true;
        }
        return false;
    }

    /**
     * 机器人账户保存
     * @param array $save
     * @param array $id
     */
    public function robotsave($data)
    {
        // $st=false;
        // print_r($data);die;
        $showpwd['password'] = !empty($data['password']) ? Util::phpEncode($data['password']) :'';
        $showpwd['paypwd'] = !empty($data['paypwd']) ? Util::phpEncode($data['paypwd']) :'';
        $saveData = [
            'password' => Util::passwordHash($data['password']),
            'paypwd' => Util::passwordHash($data['paypwd']),
            'showpwd'=>json_encode($showpwd,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
            'grade'=>'member',
            'ranges'=>0,
            'roletype'=>2,
            'status' => 1,
            'type'=>$data['type'],
        ];
        if(isset($data['number'])&&!empty($data['number'])){
            $baseconf=config('robot');
            Model::startTrans();
            try {
                for ($i=0; $i < intval($data['number']) ; $i++) { 
                    if($data['header']=='2'){
                        $saveData['header_url']='/static/header/'.rand(1, 20).'.png';
                    }
                    $characters=$baseconf['username']['midname'];
                    $username=$baseconf['username']['firstname'];
                    $nickname=$baseconf['nickname'];
                    $mobile=$baseconf['mobile']['firs'];
                    $email=$baseconf['email']['firs'];
                    $charl = strlen($characters);
                    $midstring='';
                    $num=rand(0,2);
                    for ($k=0; $k < $num; $k++) { 
                        $midstring .= $characters[random_int(0, $charl - 1)];
                    }
                    $saveData['username'] = $username[array_rand($username)].$midstring;
                    $saveData['realname'] = $nickname['firstname'][array_rand($nickname['firstname'])].$nickname['lastname'][array_rand($nickname['lastname'])].rand(0,999);
                    $saveData['mobile'] = $mobile[array_rand($mobile)].rand($baseconf['mobile']['mid'][0],$baseconf['mobile']['mid'][1]).rand($baseconf['mobile']['last'][0],$baseconf['mobile']['last'][1]);
                    $saveData['email'] = rand($baseconf['email']['name'][0],$baseconf['email']['name'][1]).$email[array_rand($email)];
                    $saveData['un_id'] = SequenceNumber::unique_ID(26);
                    $saveData['usercode'] = getRandStr(6);
                    $saveData['amount'] = rand($data['minmoney'],$data['maxmoney']);
                    $st= Model::name($this->usertable)->where('username="'.$saveData['username'].'"')->count('aid');
                    if($st<1){ Model::name($this->usertable)->insert($saveData);}
                }
                Model::commit();
                return true;
            } catch (Exception $e) {
                Model::rollback();
                $errmsg = [ 'errcode'=>$e->getCode(), 'message'=>$e->getMessage(), 'file'=>$e->getFile(), 'line'=>$e->getLine(), 'backtrace'=>getTraceAsString(),'error'=>__toString()];
                $errmsg = json_encode($errmsg,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)."\r\n";
                errlog($errmsg);
                return false;
            }   
        }
    }
}